<template>
  <!--      面包屑-->
  <div class="breadcrumb">
    <a-breadcrumb>
      <a-breadcrumb-item v-for="item in breadcrumb" class="breadcrumb-item" style="color: #707070">{{item.breadcrumbName}}</a-breadcrumb-item>
    </a-breadcrumb>
  </div>
</template>

<script setup>
import {useRoute } from 'vue-router'
const route = useRoute()
// 定义一个是否为子节点(默认有)
import {ref, watch} from "vue";
import { onMounted } from 'vue';
import DxxTag from "@/components/breadcrumb/dxxTag.vue";
// 定义面包屑数组
let breadcrumb=ref(
    [
      {
        breadcrumbName:"首页",
        path:"/"
      }
    ]
)
watch(() => route.path, () => {
  const routeList = route.matched;
  let currentBreadcrumbs = [];
  if (routeList.length > 0 && routeList[0].path === '/') {
    // 如果第一个匹配的路由是首页
    currentBreadcrumbs = [{
      breadcrumbName: "首页",
      path: "/"
    }];
  } else {
    // 如果不是首页，先添加首页
    currentBreadcrumbs = [{
      breadcrumbName: "首页",
      path: "/"
    }];
  }
  for (const routeListItem of routeList) {
    if (routeListItem.path!== '/' && routeListItem.meta.title!== undefined) {
      const existingBreadcrumb = currentBreadcrumbs.find(item => item.breadcrumbName === routeListItem.meta.title);
      if (!existingBreadcrumb) {
        currentBreadcrumbs.push({
          breadcrumbName: routeListItem.meta.title,
          path: routeListItem.path
        });
      }
    }
  }
  breadcrumb.value = currentBreadcrumbs;
});

// 页面刷新，面包屑不会不见
onMounted(() => {
  const isRefreshed =!localStorage.getItem('pageLoaded');
  if (isRefreshed) {
    console.log('页面是刷新状态。');
    localStorage.setItem('pageLoaded', 'true');
  } else {
    const routeList = route.matched;
    let currentBreadcrumbs = [];
    if (routeList.length > 0 && routeList[0].path === '/') {
      // 如果第一个匹配的路由是首页
      currentBreadcrumbs = [{
        breadcrumbName: "首页",
        path: "/"
      }];
    } else {
      // 如果不是首页，先添加首页
      currentBreadcrumbs = [{
        breadcrumbName: "首页",
        path: "/"
      }];
    }
    for (const routeListItem of routeList) {
      if (routeListItem.path!== '/' && routeListItem.meta.title!== undefined) {
        const existingBreadcrumb = currentBreadcrumbs.find(item => item.breadcrumbName === routeListItem.meta.title);
        if (!existingBreadcrumb) {
          currentBreadcrumbs.push({
            breadcrumbName: routeListItem.meta.title,
            path: routeListItem.path
          });
        }
      }
    }
    breadcrumb.value = currentBreadcrumbs;
  }
});

</script>

<style scoped>
.breadcrumb{
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: -37px;
  margin-left: 53px;
}

</style>
